package com.ruoyi.hospital.controller.order;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.hospital.domain.order.*;
import com.ruoyi.hospital.service.order.IExpressTemplateNoregionService;
import com.ruoyi.hospital.service.order.IExpressTemplateRegionService;
import com.ruoyi.hospital.service.order.IExpressTemplateService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 快递模板Controller
 * 
 * @author wendao
 * @date 2025-06-16
 */
@RestController
@RequestMapping("/hospital/expressTemplate")
public class ExpressTemplateController extends BaseController
{
    @Autowired
    private IExpressTemplateService expressTemplateService;
    @Autowired
    private IExpressTemplateNoregionService expressTemplateNoregionService;
    @Autowired
    private IExpressTemplateRegionService iExpressTemplateRegionService;

    /**
     * 查询快递模板列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ExpressTemplate expressTemplate)
    {
        startPage();

        /*用于药店端的查询*/
        if(!StringUtils.isNullOrZero(getStoreId())){
            expressTemplate.setStoreId(getStoreId());
        }

        List<ExpressTemplate> list = expressTemplateService.selectExpressTemplateList(expressTemplate);
        return getDataTable(list);
    }

    /**
     * 导出快递模板列表
     */
    @Log(title = "快递模板", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExpressTemplate expressTemplate)
    {
        List<ExpressTemplate> list = expressTemplateService.selectExpressTemplateList(expressTemplate);
        ExcelUtil<ExpressTemplate> util = new ExcelUtil<ExpressTemplate>(ExpressTemplate.class);
        util.exportExcel(response, list, "快递模板数据");
    }

    /**
     * 获取快递模板详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        ExpressTemplate expressTemplate = expressTemplateService.selectExpressTemplateById(id);
        
        //不派送
        ExpressTemplateNoregion expressTemplateNoregion = new ExpressTemplateNoregion();
        expressTemplateNoregion.setTemplateId(id);
        List<ExpressTemplateNoregion>  noRegions = new ArrayList<>();
        expressTemplate.setNoRegions(expressTemplateNoregionService.selectExpressTemplateNoregionList(expressTemplateNoregion));


        //派送的
        ExpressTemplateRegion expressTemplateRegion = new ExpressTemplateRegion();
        expressTemplateRegion.setTemplateId(id);
        List<ExpressTemplateRegion> expressTemplateRegions = iExpressTemplateRegionService.selectExpressTemplateRegionList(expressTemplateRegion);


        // 按 code 分组
        Map<String, List<ExpressTemplateRegion>> groupedByCode = expressTemplateRegions.stream()
                .collect(Collectors.groupingBy(ExpressTemplateRegion::getCode));

        List<ExpressTemplateRegion> mergedRegions = new ArrayList<>();
        for (Map.Entry<String, List<ExpressTemplateRegion>> entry : groupedByCode.entrySet()) {
            List<ExpressTemplateRegion> groupItems = entry.getValue();
            if (groupItems.isEmpty()) {
                continue;
            }
            // 取分组里第一个对象作为基础，合并 regionCodes
            ExpressTemplateRegion merged = groupItems.get(0);
            List<Region> combinedRegionCodes = new ArrayList<>();
            for (ExpressTemplateRegion item : groupItems) {
                Region region = new Region();
                region.setRegionCode(item.getRegionCode());
                region.setRegionName(item.getRegionName());
                combinedRegionCodes.add(region);
            }
            merged.setRegionCodes(combinedRegionCodes);
            mergedRegions.add(merged);
        }

        expressTemplate.setRegions(mergedRegions);

        return success(expressTemplate);
    }

    /**
     * 新增快递模板
     */
    @Log(title = "快递模板", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ExpressTemplate expressTemplate)
    {
        if(!StringUtils.isNullOrZero(getStoreId())){
            expressTemplate.setStoreId(getStoreId());
        }
        return toAjax(expressTemplateService.insertExpressTemplate(expressTemplate));
    }

    /**
     * 修改快递模板
     */
    @Log(title = "快递模板", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ExpressTemplate expressTemplate)
    {
        return toAjax(expressTemplateService.updateExpressTemplate(expressTemplate));
    }

    /**
     * 删除快递模板
     */
    @Log(title = "快递模板", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(expressTemplateService.deleteExpressTemplateByIds(ids));
    }
}
